﻿using FanaticRock.Theme.Interfaces;
using FanaticRock.ViewModels;
using System.Windows.Controls;
using System.Windows.Media;
using System.Windows.Navigation;

namespace FanaticRock.Views.Main.Pages
{
    /// <summary>
    /// MyFavoriteMusicDetailPage.xaml 的交互逻辑
    /// 收藏夹主要页面。
    /// </summary>
    public partial class MyFavoriteMusicDetailPage : PageFunction<String>, IWithParameter
    {
        public MyFavoriteMusicDetailPage()
        {
            InitializeComponent();
        }

        public async void Receive(object extraData)
        {
            // 当收到了额外的参数时，id 为b站收藏夹 id。
            if (extraData is long id)
            {
                if (DataContext is MainViewModel viewModel)
                {
                    await viewModel.CreateAlbumSongs(id);
                }
            }
        }

        private void ListBox_PreviewMouseWheel(object sender, System.Windows.Input.MouseWheelEventArgs e)
        {
            var listbox = sender as ListBox;
            if (listbox == null) return;
        }

        private void PART_ScrollViewer_MouseWheel(object sender, System.Windows.Input.MouseWheelEventArgs e)
        {
            if (e.Delta >= 0) return;
            RequestNextPage();
        }

        private void RequestNextPage()
        {
            var listView = PART_ListView;
            var scrollViewer = VisualTreeHelper.GetChild(listView, 0) as ScrollViewer;
            if (scrollViewer == null) return;
            //var scrollViewer = PART_ListView;
            var bottomOffset = (scrollViewer.VerticalOffset + scrollViewer.ViewportHeight);
            var extendHeight = scrollViewer.ExtentHeight;
            if (scrollViewer.DataContext is LazyQuerySongsViewModel lazyQuerySongsViewModel)
            {
                if (bottomOffset + 5 > extendHeight)
                {
                    ThrottleDebounce.Debouncer.Debounce(() =>
                    {
                        lazyQuerySongsViewModel.RequestNext();
                    }, TimeSpan.FromMilliseconds(500), true, false).Invoke();

                }
                else
                {

                }
            }


        }


        private void PART_ScrollViewer_ScrollChanged(object sender, ScrollChangedEventArgs e)
        {
            RequestNextPage();
        }
    }
}
